package com.fadadianqi.logistics.admin.controller;

import com.fadadianqi.logistics.admin.controller.form.AjaxResult;
import com.fadadianqi.commons.JSONProvider;
import com.fadadianqi.commons.ParamHelper;
import com.fadadianqi.goods.model.Brand;
import com.fadadianqi.goods.model.Category;
import com.fadadianqi.goods.model.Goods;
import com.fadadianqi.goods.service.GoodsService;
import com.fadadianqi.logistics.inventory.model.Backtrack;
import com.fadadianqi.logistics.inventory.model.BacktrackBatch;
import com.fadadianqi.logistics.inventory.model.Batch;
import com.fadadianqi.logistics.inventory.model.Item;
import com.fadadianqi.logistics.inventory.service.BacktrackService;
import com.fadadianqi.logistics.inventory.service.InventoryService;
import com.fadadianqi.logistics.inventory.service.StorehouseService;
import com.yeqiangwei.commons.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
public class BacktrackController {

    private static final int MAX_RESULTS = 30;

    @RequestMapping("/a/ajax/batch/item")
    public String showBatchItem(HttpServletRequest request, ModelMap modelMap) {
        String batchId = ParamHelper.getBatchId(request, null);
        Batch batch = inventoryService.getBatchById(batchId);
        modelMap.put("normalStatus", inventoryService.countNormalStatusByBatchId(batchId));
        modelMap.put("batch", batch);
        modelMap.put("goods", goodsService.getGoodsById(batch.getGoodsId()));
        modelMap.put("brand", goodsService.getBrandById(batch.getBrandId()));
        modelMap.put("category", goodsService.getCategoryById(batch.getCategoryId()));
        modelMap.put("popValues", goodsService.findGoodsPropValueByGoodsId(batch.getGoodsId()));
        modelMap.put("storehouse", storehouseService.getStorehouseById(batch.getStorehouseId()));
        return "/admin/store/batchItem";
    }

    @RequestMapping(value = "/a/store/backtrack/print", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> print(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String id = ParamUtils.getString(request, "id", null);
        AjaxResult rs = null;
        try {
            backtrackService.doPrint(id);
            rs = new AjaxResult(null, Boolean.TRUE, null);
        } catch (Exception e) {
            e.printStackTrace();
            rs = new AjaxResult(null, Boolean.FALSE, null);
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/store/backtrack/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> save(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String json = ParamUtils.getString(request, "json", null);
        BacktrackForm form = (BacktrackForm) JSONProvider.toBean(json, BacktrackForm.class);
        AjaxResult rs = null;
        try {
            backtrackService.doBack(form);
            rs = new AjaxResult(null, Boolean.TRUE, null);
        } catch (Exception e) {
            e.printStackTrace();
            rs = new AjaxResult(null, Boolean.FALSE, null);
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping(value = "/a/store/backtrack/cancel/save", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<String> cancel(HttpServletRequest request, ModelMap modelMap) {
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "text/html; charset=utf-8");
        String id = ParamHelper.getId(request, null);
        AjaxResult rs = null;
        try {
            backtrackService.cancel(id);
            rs = new AjaxResult(null, Boolean.TRUE, null);
        } catch (Exception e) {
            e.printStackTrace();
            rs = new AjaxResult(null, Boolean.FALSE, null);
        }
        return new ResponseEntity<String>(JSONProvider.toJSON(rs),
                responseHeaders, HttpStatus.OK);
    }

    @RequestMapping("/a/store/backtrack/cancel/form")
    public String cancelForm(HttpServletRequest request, ModelMap modelMap) {
        String id = ParamHelper.getId(request, null);
        modelMap.put("id", id);
        return "/admin/store/backtrackCancelForm";
    }

    @RequestMapping("/a/store/backtrack/form")
    public String showForm(HttpServletRequest request, ModelMap modelMap) {
        String goodsId = ParamHelper.getGoodsId(request, null);
        String batchId = ParamHelper.getBatchId(request, null);
        Goods goods = goodsService.getGoodsById(goodsId);
        if (ValidatorHelper.isNotEmpty(batchId)) {
            Batch batch = inventoryService.getBatchById(batchId);
            if (batch != null) {
                goods = goodsService.getGoodsById(batch.getGoodsId());
            }
        }
        modelMap.put("goods", goods);
        modelMap.put("batchId", batchId);
        modelMap.put("goodsId", goodsId);
        return "/admin/store/backtrackForm";
    }

    @RequestMapping("/a/store/backtrack")
    public String showList(HttpServletRequest request, ModelMap modelMap) {
        Pagination pagination = new Pagination(request, MAX_RESULTS);
        List<Backtrack> list = backtrackService.findAll(pagination);
        pagination.setTotal(backtrackService.count());
        PaginationHelper.setAttribute(request, pagination);
        List<BacktrackVO> voList = new ArrayList<BacktrackVO>();
        if (ValidatorHelper.isNotEmpty(list)) {
            for (Backtrack backtrack : list) {
                BacktrackVO vo = new BacktrackVO();
                BeanUtils.copyProperties(vo, backtrack);
                List<ItemVO> items = new ArrayList<ItemVO>();
                List<BacktrackBatch> bbs = backtrackService.findBatchByBacktrackId(backtrack.getId());
                for (BacktrackBatch bb : bbs) {
                    Batch batch = inventoryService.getBatchById(bb.getBatchId());
                    ItemVO item = new ItemVO();
                    BeanUtils.copyProperties(item, batch);
                    item.setCount(bb.getCount());
                    item.setCategory(goodsService.getCategoryById(item.getCategoryId()));
                    item.setBrand(goodsService.getBrandById(item.getBrandId()));
                    item.setGoods(goodsService.getGoodsById(item.getGoodsId()));
                    items.add(item);
                }
                vo.setItems(items);
                voList.add(vo);
            }
        }
        modelMap.put("list", voList);
        return "/admin/store/backtrackList";
    }

    @Autowired
    private StorehouseService storehouseService;

    @Autowired
    private BacktrackService backtrackService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private GoodsService goodsService;

    public class BacktrackVO extends Backtrack {

        /**
         *
         */
        private static final long serialVersionUID = 4904649395714786707L;

        private List<ItemVO> items;

        public List<ItemVO> getItems() {
            return items;
        }

        public void setItems(List<ItemVO> items) {
            this.items = items;
        }
    }

    public class ItemVO extends Item implements java.io.Serializable {

        /**
         *
         */
        private static final long serialVersionUID = -3118751648884379999L;

        private Goods goods;

        private Brand brand;

        private Category category;

        private int count; // 退回数量


        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public Goods getGoods() {
            return goods;
        }

        public void setGoods(Goods goods) {
            this.goods = goods;
        }

        public Brand getBrand() {
            return brand;
        }

        public void setBrand(Brand brand) {
            this.brand = brand;
        }

        public Category getCategory() {
            return category;
        }

        public void setCategory(Category category) {
            this.category = category;
        }
    }

    public static class BacktrackForm implements java.io.Serializable {

        /**
         *
         */
        private static final long serialVersionUID = -1444349692986719240L;
        private List<BacktrackItemForm> items;
        private String memo;
        private double money;
        private Boolean needPrint = Boolean.TRUE;

        public Boolean getNeedPrint() {
            return needPrint;
        }

        public void setNeedPrint(Boolean needPrint) {
            this.needPrint = needPrint;
        }

        public List<BacktrackItemForm> getItems() {
            return items;
        }

        public void setItems(List<BacktrackItemForm> items) {
            this.items = items;
        }

        public String getMemo() {
            return memo;
        }

        public void setMemo(String memo) {
            this.memo = memo;
        }

        public double getMoney() {
            return money;
        }

        public void setMoney(double money) {
            this.money = money;
        }
    }

    public static class BacktrackItemForm implements java.io.Serializable {

        /**
         *
         */
        private static final long serialVersionUID = -7122602617218550L;
        private String batchId;
        private int count;

        public String getBatchId() {
            return batchId;
        }

        public void setBatchId(String batchId) {
            this.batchId = batchId;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }
    }
}
